//
//  NSString+JXCommon.m
//  jiuxian
//
//  Created by tianzhenzi on 15/8/5.
//  Copyright (c) 2015年 jiuxian.com. All rights reserved.
//

@implementation NSString (JXCommon)

/**
 URL编码
 */
- (NSString *)urlEncoding {
    NSString *str = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef) self, NULL, (CFStringRef) @"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    return [str stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
}

/**
 URL解码
 */
- (NSString *)urlDecoding {
    return [[self stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)stringByURLDecode {
    if ([self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
        return [self stringByRemovingPercentEncoding];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
        NSString *decoded = [self stringByReplacingOccurrencesOfString:@"+"
                                                            withString:@" "];
        decoded = (__bridge_transfer NSString *)
        CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
                                                                NULL,
                                                                (__bridge CFStringRef)decoded,
                                                                CFSTR(""),
                                                                en);
        return decoded;
#pragma clang diagnostic pop
    }
}

-(NSString *)URLDecodedString
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}

- (NSString *)bigImageUrl {
    NSRange range = [self rangeOfString:@"." options:NSBackwardsSearch];
    NSString *forwardStr = [self substringToIndex:range.location - 1];
    NSString *backStr = [self substringFromIndex:range.location];
    NSString *bigImageUrl = [NSString stringWithFormat:@"%@%@", forwardStr, backStr];
    return bigImageUrl;
}

/**
 判断字符串是否是条码
 */
- (BOOL)isBarcode {
    NSString *numberRegex = @"^[0-9]*$";
    NSPredicate *numPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
    return [numPre evaluateWithObject:[self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

/**
 判断是否是url
 */
- (BOOL)isUrl {
    NSString *urlRegex = @"[a-zA-z]+://[^\\s]*";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegex];
    return [urlTest evaluateWithObject:[self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

/**
 判断是否是email
 */
- (BOOL)isEmail {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

/**
 判断是否是手机号
 */
- (BOOL)isMobile {
    //手机号以13， 15，18开头，八个 \d 数字字符
    //添加 147 170号段
    //    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])|(147)|(170))\\d{8}$";

    /**
     目前APP端只校验数字类型，并且位数是11位的，手机号格式校验交给服务器来判断
     */

    NSString *phoneRegex = @"^\\d{11}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

/**
 判断是否是电话号码
 */
- (BOOL)isPhone {
    NSString *phoneRegex = @"((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

/**
 验证密码格式，数字 字母 符号 组合
 */
- (BOOL)isPassWord {
    NSString *phoneRegex = @"^[A-Za-z0-9!$#%@^&*_-~)(/.,\';+:]+$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

/**
 判断是否是身份证
 */
- (BOOL)isIdCard {
    //身份证为15位或者18位，15位的全为数字，18位的前17位为数字，最后一位为数字或者大写字母”X“
    NSString *idCardRegex = @"(^\\d{15}$)|(^\\d{17}([0-9]|X)$)";
    NSPredicate *idCardTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", idCardRegex];
    return [idCardTest evaluateWithObject:self];
}

/**
 根据身份证号获取生日:YYYY-MM-dd字符串
 如果非身份证格式或为空字符串 返回nil
 */
- (NSString *)birthdayWithIdCard {
    if ([self isIdCard]) {
        NSMutableString *result = [NSMutableString stringWithCapacity:0];
        NSString *year = nil;
        NSString *month = nil;
        NSString *day = nil;

        year = [self substringWithRange:NSMakeRange(6, 4)];
        month = [self substringWithRange:NSMakeRange(10, 2)];
        day = [self substringWithRange:NSMakeRange(12, 2)];

        [result appendString:year];
        [result appendString:@"-"];
        [result appendString:month];
        [result appendString:@"-"];
        [result appendString:day];
        return result;
    }
    return nil;
}

/**
 判断日期格式：YYYY-MM-dd
 */
- (BOOL)isDateForYYYY_MM_dd {
    NSString *dateRegex = @"^\\d{4}-\\d{1,2}-\\d{1,2}$";
    NSPredicate *dateTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", dateRegex];
    return [dateTest evaluateWithObject:self];
}

- (CGSize)adjustHeightWithFont:(UIFont *)font width:(CGFloat)width {
    return [self jkdSizeWithFont:font
               constrainedToSize:CGSizeMake(width, MAXFLOAT)
                   lineBreakMode:NSLineBreakByWordWrapping];
}

- (CGSize)jkdSizeWithFont:(UIFont *)font
        constrainedToSize:(CGSize)size
            lineBreakMode:(NSLineBreakMode)lineBreakMode {
    CGSize returnSize = CGSizeZero;
    if ([NSString instancesRespondToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        NSDictionary *attribute = @{NSFontAttributeName : font};
        returnSize = [self boundingRectWithSize:size
                                        options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                     attributes:attribute
                                        context:nil]
                .size;
    }
    return returnSize;
}



- (CGSize)jx_SizeWithFont:(UIFont *)font
        constrainedToSize:(CGSize)size
                lineSpace:(CGFloat)lineSpace
           numberOfLines:(NSInteger)lines{
    CGSize returnSize = CGSizeZero;
    CGSize defaultSize = CGSizeZero;
    CGSize textBlockMinSize = size;
    static float systemVersion;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    });
    if (systemVersion >= 7.0) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        if (lineSpace) {
            [paragraphStyle setLineSpacing:lineSpace];//调整行间距
        }
        returnSize = [self boundingRectWithSize:textBlockMinSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                               attributes:@{
                                            NSFontAttributeName:font,
                                            NSParagraphStyleAttributeName:paragraphStyle
                                            }
                                  context:nil].size;
        if (lines == 0) {
            return returnSize;
        }
        NSMutableString *defaultStr = [[NSMutableString alloc] init];
        for (NSInteger i = 0; i<lines; i++) {
            if (i == 0) {
                [defaultStr appendString:@"你好"];
            }else{
                [defaultStr appendString:@"\n你好"];
            }
        }
        defaultSize = [defaultStr boundingRectWithSize:textBlockMinSize options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : font,
                                                        NSParagraphStyleAttributeName : paragraphStyle
                                                        }
                                              context:nil].size;
    }
    return returnSize.height > defaultSize.height ? defaultSize : returnSize;
}

- (CGSize)jx_SizeWithFont:(UIFont *)font
        constrainedToSize:(CGSize)size
                lineSpace:(CGFloat)lineSpace
            numberOfLines:(NSInteger)lines
               attributes:(NSDictionary *)attributes{
    CGSize returnSize = CGSizeZero;
    CGSize defaultSize = CGSizeZero;
    CGSize textBlockMinSize = size;
    static float systemVersion;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    });
    if (systemVersion >= 7.0) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        if (lineSpace) {
            [paragraphStyle setLineSpacing:lineSpace];//调整行间距
        }
        NSDictionary *defaultAttributes = [[NSMutableDictionary alloc] initWithDictionary:@{
                                                                                            NSFontAttributeName:font,
                                                                                            NSParagraphStyleAttributeName:paragraphStyle
                                                                                            }];
        [defaultAttributes setValuesForKeysWithDictionary:attributes];
        returnSize = [self boundingRectWithSize:textBlockMinSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                     attributes:defaultAttributes
                                        context:nil].size;
        if (lines == 0) {
            return returnSize;
        }
        NSMutableString *defaultStr = [[NSMutableString alloc] init];
        for (NSInteger i = 0; i<lines; i++) {
            if (i == 0) {
                [defaultStr appendString:@"你好"];
            }else{
                [defaultStr appendString:@"\n你好"];
            }
        }
        defaultSize = [defaultStr boundingRectWithSize:textBlockMinSize options:NSStringDrawingUsesLineFragmentOrigin
                                            attributes:defaultAttributes
                                               context:nil].size;
    }
    return returnSize.height > defaultSize.height ? defaultSize : returnSize;
}


- (CGSize)jx_SizeWithFont:(UIFont *)font
        constrainedToSize:(CGSize)size{
    
    CGSize returnSize = CGSizeZero;
    
    CGSize textBlockMinSize = size;
    static float systemVersion;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    });
    if (systemVersion >= 7.0) {
        returnSize = [self boundingRectWithSize:textBlockMinSize options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{
                                                  NSFontAttributeName:font
                                                  }
                                        context:nil].size;
        size =returnSize;
    }
    return size;
}

- (NSString *)replaceNil {
    return [[self stringByReplacingOccurrencesOfString:@"(null)" withString:@""]
            stringByReplacingOccurrencesOfString:@"<null>"
                                      withString:@""];
}

+ (NSString *)priceDisplayWithStr:(double)price {
    NSString *str = [NSString stringWithFormat:@"%f", price];

    NSRange range = [str rangeOfString:@"." options:NSBackwardsSearch];
    NSString *forwardStr = [str substringToIndex:range.location]; //.前的
    NSString *backStr = [str substringFromIndex:range.location];

    NSRange r = NSMakeRange(1, 2);

    NSString *lastNum = [backStr substringWithRange:r]; //.后的
    NSRange secRange = NSMakeRange(1, 1);
    NSString *sec = [lastNum substringWithRange:secRange];
    if ([sec isEqualToString:@"0"]) {
        backStr = [backStr substringWithRange:NSMakeRange(0, 2)];
        //9.0 取9
        if ([[backStr substringWithRange:NSMakeRange(1, 1)] isEqualToString:@"0"]) {
            backStr = nil;
        }
    }
    else {
        backStr = [backStr substringWithRange:NSMakeRange(0, 3)];
    }
    NSString *newPrice = [[NSString stringWithFormat:@"%@%@", forwardStr, backStr] replaceNil];

    return newPrice;
}

/**
 输入值是空格的
 */
- (BOOL)isEmpty {
    NSCharacterSet *charSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmed = [self stringByTrimmingCharactersInSet:charSet];
    return [trimmed isEqualToString:@""];
}
/**
 字符串是否为空的 空：YES 否：NO
 */
+ (BOOL)isEmptyWithString:(NSString *)string{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

- (BOOL)isValidString{
    if ([self isKindOfClass:[NSNull class]]||[self isEmpty]||self ==NULL) {
        return NO;
    }else{
        return YES;
    }
}

- (UIImage *)forumMyLevelImage{
    return [UIImage imageNamed:[NSString stringWithFormat:@"JXForum_my_level_%@",self]];
}

- (UIImage *)forumOtherLevelImage{
    return [UIImage imageNamed:[NSString stringWithFormat:@"JXForum_other_level_%@",self]];
}

/**
 *特殊字过滤
 *  @ string  字符串
 *  @ character  特殊字符
 *  @ return  过滤后侧字符串
 */
-(NSString *)stringOfSpecialCharacter:(NSString *)string character:(nonnull NSString *)character
{
    NSString *tempString =nil;
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:character];
   tempString = [[string componentsSeparatedByCharactersInSet: doNotWant]componentsJoinedByString:@""];
    return tempString;
}

- (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)constrainSize{
    CGSize size = CGSizeZero;
    CGRect rect = [self boundingRectWithSize:constrainSize//限制最大的宽度和高度
                                     options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                  attributes:@{NSFontAttributeName : font}//传人的字体字典
                                     context:nil];
    size = rect.size;
    return size;
}


@end
